package com.itita.weibo.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import weibo4andriod.Status;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.itita.weibo.manager.IWeiboActivity;
import com.itita.weibo.manager.MainService;
import com.itita.weibo.model.RecommendStatusAdapter;
import com.itita.weibo.model.Task;
import com.itita.weibo.util.WeiboUtil;


/**
 * 主要负责Tab间的切换
 * 
 * @author 焦明
 * 2010-5-5 00:00
 *
 */
public final class ListRcemmendInfoActivity extends Activity implements IWeiboActivity{
   
	public static  boolean IS_GET_REF_OR_MORE_RECOMMENTD_STATUS_FROM_NET = false;
	
	public static final String REF_WEIBO="REF_WEIBO";//更新微博 
    
    public static final String REF_ICON="REF_ICON";//更新头像
    
    public static final String REF_WEIBO_MORE="REF_WEIBO_MORE";//更多信息
    
    public static final String REF_NEW_WEIBO_RESULT="REF_NEW_WEIBO_RESULT";//发表微博的结果
   
    public static final String REF_NEW_WEIBO_COMM_RESULT="REF_NEW_WEIBO_RESULT";//发表微博的结果
   
    public static final String REF_VERIFY_RESULT = "REF_VERIFY_RESULT";
    //加载微博中的图片
    public static final String REF_GET_WEIBO_IMAGE = "REF_GET_WEIBO_IMAGE";
    
    public final int pagesize=10;
    
    public  int nowpage=1;
    
    public int basePageSize = 20;
    
    
    private ListView listView;
    
    private  View process;
    
    private Button btRefbolg;
	
    private TextView tvFresh;

    private TextView tvMore;

    private View loadReFreshProcess;
    
    private View loadMoreProcess;
    
    private View  reloadProgressBar;
    
    protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.recommend_info);
			//请求当前用户的微博主页 
			final HashMap hm=new HashMap();
			hm.put("pagesize", pagesize);
			hm.put("nowpage", nowpage); //请求当前用户的微博主页 
			Task tsHome=new Task(Task.TASK_GET_USER_RECOMMEND_INFO_HOME_INLINE, hm);
			
		    MainService.newTaskToTaskQueneHead(tsHome);
//		}
	
	    
	    MainService.addActivity(this);
	   
	   
	    this.initControlsAndAddControlsEvent();
	    //注册上下文菜单
        this.registerForContextMenu(listView);
	}
    
    @Override
	public final void initControlsAndAddControlsEvent() {
    	
    	 //获取列表对象和进度条对象
	    process=this.findViewById(R.id.progress4RecommendInfo);
	    listView=(ListView)this.findViewById(R.id.listview4RecommendInfo);
		   
	    //条目可点击
//	    listView.setClickable(true);
		  //获取标题
    	final View titleview=this.findViewById(R.id.title4RecommendInfo);
    	final TextView tv=(TextView)titleview.findViewById(R.id.textView);
        tv.setText(R.string.recommendInfo);
//	    tv.setTextSize((float) 17.0);
	    tv.setVisibility(View.VISIBLE);
//		 final ImageView imageViewTitle = (ImageView) titleview.findViewById(R.id.imageViewTitle);
//		 imageViewTitle.setImageResource(R.drawable.pr_resys);
		 
    	
    	btRefbolg=(Button)titleview.findViewById(R.id.title_bt_right);
    	
    	this.reloadProgressBar = titleview.findViewById(R.id.rlProgressBar);
    	
    	//当前用户的昵称
//	    tv.setText(MainService.currentUser.getName());
	    
	    
	    Button btNewbolg=(Button)titleview.findViewById(R.id.title_bt_left);
	    btNewbolg.setBackgroundResource(R.drawable.title_new);
	    btNewbolg.setOnClickListener(new OnClickListener(){
 	        
			public void onClick(View v) {
		    //进入发表微博窗口
 	    	   Intent itnewblog=new Intent(ListRcemmendInfoActivity.this,NewWeiboActivity.class);
 	    	   ListRcemmendInfoActivity.this.startActivityForResult(itnewblog, 1);
 	       }
	    }
	    );
	   
	    btRefbolg.setBackgroundResource(R.drawable.title_reload);
	    btRefbolg.setOnClickListener(new OnClickListener(){     
			 public void onClick(View arg0) {
				 
			    btRefbolg.setVisibility(View.GONE); 
			    reloadProgressBar.setVisibility(View.VISIBLE); 
			    
		     		//添加获取首页信息任务
		    	final HashMap hm=new HashMap();
				hm.put("pagesize", pagesize);
				hm.put("nowpage", nowpage);  
		    	Task tsHome=new Task(Task.TASK_GET_USER_RECOMMEND_INFO_HOME_INLINE_REFRESH, hm);
		    	MainService.newTaskToTaskQueneHead(tsHome);
		    	//打开数据离线的存储开关
				MainService.isWillSaved = true;
			}
	    }
	    );

	    
	    //对ListView进行事件处理
	    listView.setOnItemClickListener(new OnItemClickListener(){
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if(arg3==-1){  //更多
//					WeiboUtil.myToastShow(ListRcemmendInfoActivity.this, "获取更多数据");

					loadMoreProcess = arg1.findViewById(R.id.footOrHeadLoadingBar);
                	loadMoreProcess.setVisibility(View.VISIBLE);    
                	tvMore = (TextView) arg1.findViewById(R.id.tvItemContent);
					tvMore.setText(R.string.loading);
					
					//打开数据离线的存储开关
					MainService.isWillSaved = true;
					ListRcemmendInfoActivity.IS_GET_REF_OR_MORE_RECOMMENTD_STATUS_FROM_NET = true;
					
					
					nowpage++;
					final HashMap hm=new HashMap();
					hm.put("pagesize", pagesize);
					hm.put("nowpage", nowpage);
					hm.put("basePageSize", basePageSize);
					Task tsHome=new Task(Task.TASK_GET_USER_RECOMMEND_INFO_HOME_INLINE_MORE, hm);
//					MainService.addNewTask(tsHome);
					MainService.newTaskToTaskQueneHead(tsHome);
				}
				else if(arg3==0)  //刷新
                {   
					loadReFreshProcess = arg1.findViewById(R.id.footOrHeadLoadingBar);
	                loadReFreshProcess.setVisibility(View.VISIBLE);    
					tvFresh = (TextView) arg1.findViewById(R.id.tvItemContent);
					tvFresh.setText(R.string.loading);
					

					btRefbolg.setVisibility(View.GONE); 
					reloadProgressBar.setVisibility(View.VISIBLE); 
					
					ListRcemmendInfoActivity.IS_GET_REF_OR_MORE_RECOMMENTD_STATUS_FROM_NET = true;
					   
					final HashMap hm=new HashMap();
					hm.put("pagesize", pagesize);
					hm.put("nowpage", nowpage);
					hm.put("basePageSize", basePageSize);
			    	Task tsHome=new Task(Task.TASK_GET_USER_RECOMMEND_INFO_HOME_INLINE_REFRESH,hm);
			    	MainService.newTaskToTaskQueneHead(tsHome);
				}
				else{
				    Intent it=new Intent(ListRcemmendInfoActivity.this,ViewWeiboActivity.class);
				   try{
					   RecommendStatusAdapter ma=(RecommendStatusAdapter)listView.getAdapter();
					    Status statu=(Status)ma.allstatus.get(arg2-1);
					    it.putExtra("status",statu);
				    }catch(Exception e){
				    	Log.e("e","error"+e);
				    }
//				    
				    ListRcemmendInfoActivity.this.startActivityForResult(it, 0);
				}
//				
			}
	    	
	    });
	}
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo am=(AdapterContextMenuInfo)item.getMenuInfo();
		Intent intent = null;
		switch(item.getItemId())
	    {case 1://
	    	Toast.makeText(this, "您要转发"+am.id,1000).show();
	    	break;
	    case 2://
	    	Toast.makeText(this, "您要评论列表第"+am.position+"项",1000).show();
	    	intent = new Intent(this, CommentActivity.class);
	    	intent.putExtra("statusId", am.id);
			startActivity(intent);
	    	break;
	    case 3://
	    	new FavThread(am.id).start();
	    	break;
	    case 4://
	    	Toast.makeText(this, "您要查看信息",1000).show();
	    	break;
	    }
		return super.onContextItemSelected(item);
	
	
	}
	 
	public void onContextMenuClosed(Menu menu) {
   }
	
	//初始化上下文菜单
	 
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		AdapterContextMenuInfo am=(AdapterContextMenuInfo)menuInfo;
		
		if(am.position==0)//刷新
		{
			return;
		}
		if(am.id==-1)//更多
		{
			return;
		}
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle("微博功能操作");
		//      组编号 项编号 排列顺序
		menu.add(1, 1, 1, "转发");
		menu.add(1, 2, 2, "评论");
		menu.add(1, 3, 3, "收藏");
		menu.add(1, 4, 4, "查看用户信息");
		
	}
	 
	public void init() {
		
	}
	 
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Log.d("keydown", ".................."+keyCode);
		if(keyCode==4)//如果用户按下了返回键
		{
			MainService.promptExitApp(this);
		}
		return true;
	}
	 
	public void refresh(Object... param) {
		Log.d("ref", (String)param[0]);
		String flag = (String)param[0];

		if (flag.equals("REF_WEIBO")) {
			
			if(this.process.VISIBLE == View.VISIBLE){
				this.process.setVisibility(View.GONE);				
			}
			
			if(this.reloadProgressBar.VISIBLE == View.VISIBLE){
				this.reloadProgressBar.setVisibility(View.GONE);
				this.btRefbolg.setVisibility(View.VISIBLE);
			}
			
			if(this.loadReFreshProcess != null && this.loadReFreshProcess.VISIBLE == View.VISIBLE){
				this.loadReFreshProcess.setVisibility(View.GONE);
				this.tvFresh.setText(R.string.refresh);
			}
			
			if(param[1] == null){
				WeiboUtil.myToastShow(this, "网络连接错误");
				return;
			}else{
				RecommendStatusAdapter recommendStatusAdapter = new RecommendStatusAdapter(this, (ArrayList<Status>) param[1]);
				listView.setAdapter(recommendStatusAdapter);// 更新列表
			}
			
			if(!MainService.isVerifySucc){ //如果自动登陆验证失败ss
				//添加用户校验任务
			    Task tsVerifyUserTask = new Task(Task.TASK_USER_LOGIN);
			    MainService.addNewTask(tsVerifyUserTask);
			}
			 
	        if(param[1] != null && MainService.isVerifySucc && ListRcemmendInfoActivity.IS_GET_REF_OR_MORE_RECOMMENTD_STATUS_FROM_NET){
	        	HashMap mHashMap = new HashMap();
				mHashMap.put("statuses", (ArrayList<Status>) param[1]);
				Task taskHome = new Task(Task.TASK_ADD_MORE_STATUS_TO_LOCAL, mHashMap);
				MainService.newTask(taskHome);
				////System.out.println("--------------refresh添加存储数据到 笨的任务------------------");
				ListRcemmendInfoActivity.IS_GET_REF_OR_MORE_RECOMMENTD_STATUS_FROM_NET = false;
	        }
			
			    //关闭存储
			
		} else if (flag.equals(REF_ICON)) {
			// 让数据适配器getView方法重新调用
			((RecommendStatusAdapter) listView.getAdapter()).notifyDataSetChanged();
		}

		else if (flag.equals(REF_WEIBO_MORE)) { //刷新更多数据
			if(this.loadMoreProcess != null && this.loadMoreProcess.VISIBLE == View.VISIBLE){
				this.loadMoreProcess.setVisibility(View.GONE);
				this.tvMore.setText(R.string.more);
			}
			if(param[1] == null){
				WeiboUtil.myToastShow(this, "网络连接失败, 获取更多信息失败");
				return;
			}
			
			List<Status> alls = (List<Status>) param[1];
			((RecommendStatusAdapter) listView.getAdapter()).addMoreData(alls);
		}

		else if (flag.equals(REF_NEW_WEIBO_RESULT)) {
			String result = (String) param[1];
			WeiboUtil.myToastShow(this, result);
		}

		else if (flag.equals(REF_NEW_WEIBO_COMM_RESULT)) {
			String result = (String) param[1];
			WeiboUtil.myToastShow(this, result);
		}

		// 刷新微博中的图片
		else if (flag.equals(REF_GET_WEIBO_IMAGE)) {
			// 让数据适配器getView方法重新调用
			((RecommendStatusAdapter) listView.getAdapter()).notifyDataSetChanged();
		}
//		
//		// 
//		else if (flag.equals(REF_VERIFY_RESULT)) {
//			 String result = (String) param[1];
//			 if(result.indexOf("错误") > 0){
//				 WeiboUtil.myToastShow(this, "由于网络原因");
//			 }
//		}
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		 
		super.onActivityResult(requestCode, resultCode, data);
		switch (resultCode){
	      case RESULT_OK: /* 取得数据，并显示于画面上 */
	         Bundle bunde = data.getExtras();
	         String newBolgResultMsg = bunde.getString("newBlogResult");
	         Toast.makeText(this, newBolgResultMsg, Toast.LENGTH_SHORT).show();
	         break;
	         
	      default:
	        break;
	    }
	}

  
	@Override
	protected void onResume() {
		super.onResume();
		// 检查网络
		if (!WeiboUtil.checkNet(this)) {// 联网正常
			Log.d("检查网络", "网络异常");
		    WeiboUtil.myToastShow(this, "网络连接失败");
		} 
	}
	 private  Handler myHandler =  new Handler(){
		  public void handleMessage(android.os.Message msg) {
			  if(msg.obj != null){
				  WeiboUtil.myToastShow(ListRcemmendInfoActivity.this, "收藏成功");
			  }else{
				  WeiboUtil.myToastShow(ListRcemmendInfoActivity.this, "收藏失败");
			  }
		  }
	  };		
	
 private class FavThread extends Thread {
	     
		 private long statusId;
		 
		 public FavThread(long statusId){
			 this.statusId = statusId; 
		 }
		 
		 Message message = myHandler.obtainMessage();
		 public void run() {
			try {
			   Status status= MainService.mainService.weibo.createFavorite(statusId); 
			   message.obj= status;
			} catch (Exception e) {
				message.obj = null;
				e.printStackTrace();
			}
			//见消息压入消息队列
			myHandler.sendMessage(message);	
		 }
	  }

}
